var app = getApp();
var QQMapWX = require('../../../mymap/qqmap-wx-jssdk.min.js');
var qqmapsdk;
var location = require("../../../mybehaviors/location/location");
Page({
  behaviors: [location],
  /**
   * 页面的初始数据
   */
  data: {
    language: '',
    height: '',
    /*地图数据*/
    point: {
      lat: '',
      lng: ''
    },
    city: '',
    address: '',
    suggestionshow: false,
    suggestion: [],
    /**/
    classificationshow: false,
    Locationshow: false,
    commodityTitle: '',
    addgoodslistshow: false,
    goodsdata: '',
    storeshow: false,
    storedata: '',
    protocolshow: false,
    photosize: 1024 * 1024 * 4, // 图片大小限制
    uploadUrl: 'upload.uploadPic',
    catelist: [],
    catname: '',
    goodslistData: [],
    goodsisLoadMore: true,
    goodsPage: 1,
    goodsTotal: 0,
    selectgoodsData: {},
    storelistData: [],
    storePage: 1,
    storeTotal: 0,
    storeisLoadMore: true,
    selectstoreData: {},
    imgData: [],
    releasetitle: '',
    releasecontents: '',
    catid: '',
    releaseaddress: '',
    releasecity: '',
    releaselat: '',
    releaselnt: '',
    goodsId: '',
    storeId: '',
    checked: true,
    agreementcontent: '',
    stickid: '',

    audio_open: 0, //是否开启音频上传
    audioPath: [], //上传的音频路径
    audioList: [] //上传的音频链接
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (!app.globalData.qqmapkey) {
      app._getTemplate().then(res => {
        qqmapsdk = new QQMapWX({
          key: app.globalData.qqmapkey
        });
      });
    } else {
      qqmapsdk = new QQMapWX({
        key: app.globalData.qqmapkey
      });
    }

    if (options.stickid&&Number(options.stickid)!=0) {
      this.setData({
        stickid: options.stickid
      });
      this.getMicroCommentDetails();
    } else {
      wx.navigateBack({
        delta: 1
      });
    }
    this._getLocation(() => {});

    this.getAgreement();
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          height: res.windowHeight - 70
        });
      }
    });
  },

  removeImg(e) {
    let index = e.currentTarget.dataset.index;
    this.data.imgData.splice(index, 1);
    this.setData({
      imgData: this.data.imgData
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onShareTimeline:function(){},
  getAgreement() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.micro-communities.api.trick.getAgreement");
    // let dataJson = {};
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            agreementcontent: res.data ? res.data.value : '',
            audio_open: (res.data ? Number(res.data.audio_open) : 0)
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  // 选择图片
  onRead() {
    let that = this;
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        wx.compressImage({
          src: tempFilePaths[0], // 图片路径
          quality: 60, // 压缩质量
          success(e) {
            let photourl = e.tempFilePath;
            wx.uploadFile({
              url: urlStr,
              filePath: photourl,
              name: 'file',
              success(resdata) {
                var res = JSON.parse(resdata.data);
                if (res.result == 1) {
                  let imageUrl1 = res.data.img_url;
                  let imgData = that.data.imgData;
                  imgData.push(imageUrl1);
                  that.setData({
                    imgData: imgData
                  });
                } else {
                  wx.showToast({
                    icon: 'none',
                    title: res.msg,
                    duration: 1500
                  });
                }
              }
            });
          },
          fail(e) {},
          complete(e) {}
        });
      }
    });
  },
  releasetitleInp(e) {
    let val = e.detail.value;
    this.setData({
      releasetitle: val
    });
  },
  releasecontentsInp(e) {
    let val = e.detail.value;
    this.setData({
      releasecontents: val
    });
  },
  getClassification() {
    this.setData({
      classificationshow: true
    });
    this.getClassificationData();
  },
  getClassificationData() {
    let that = this;
    let json = {};
    let urlStr = app.getNetAddresss("plugin.micro-communities.api.index.getCate");
    if (this.data.commodityTitle) {
      json.cName = this.data.commodityTitle;
    }
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            catelist: res.data.data
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getReleaseAddress() {
    this.address_detail = '';
    this.setData({
      Locationshow: true
    });
  },
  getGoodsMessage() {
    this.getGoodsMessageData();
    this.setData({
      addgoodslistshow: true
    });
  },
  getStoreMessage() {
    this.getStoreMessageData();
    this.setData({
      storeshow: true
    });
  },
  getStoreMessageData() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.micro-communities.api.trick.getStore");
    let json = {};
    json.store_name = this.data.storedata;
    that.setData({
      storePage: 1 //数组拼接
    });
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            storelistData: res.data.data,
            storeTotal: res.data.last_page
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getStoreMoreData() {
    const that = this;
    that.data.storeisLoadMore = false; // 防止多次请求分页数据
    if (this.data.storePage >= this.data.storeTotal) {
      return;
    } else {
      this.data.storePage = this.data.storePage + 1;
      let urlStr = app.getNetAddresss("plugin.micro-communities.api.trick.getStore");
      app._getNetWork({
        url: urlStr,
        data: {
          page: that.data.storePage,
          store_name: that.data.storedata
        },
        success: function (resdata) {
          var res = resdata.data;
          that.data.storeisLoadMore = true;
          if (res.result == 1) {
            let myData = res.data.data;
            console.log(that.data.storelistData);
            that.setData({
              storelistData: that.data.storelistData.concat(myData) //数组拼接
            });
          } else {
            that.data.storePage = that.data.storePage - 1;
            that.data.storeisLoadMore = false;
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  openProtocol() {
    this.setData({
      protocolshow: true
    });
  },
  submitBtn() {
    // if (this.data.imgData.length == 0) {
    //   wx.showToast({
    //     icon: 'none',
    //     title: '请上传图片',
    //     duration: 1500
    //   });
    //   return;
    // }
    if (!this.data.releasetitle) {
      wx.showToast({
        icon: 'none',
        title: '请填写标题',
        duration: 1500
      });
      return;
    }
    if (!this.data.releasecontents) {
      wx.showToast({
        icon: 'none',
        title: '请添加正文',
        duration: 1500
      });
      return;
    }
    if (!this.data.catid) {
      wx.showToast({
        icon: 'none',
        title: '请选择分类',
        duration: 1500
      });
      return;
    }
    // if (!this.data.releaseaddress) {
    //   wx.showToast({
    //     icon: 'none',
    //     title: '请选择地点',
    //     duration: 1500
    //   });
    //   return;
    // }
    // if (!this.data.goodsId) {
    // 	wx.showToast({
    // 		icon: 'none',
    // 		title: '请添加商品',
    // 		duration: 1500
    // 	})
    // 	return
    // }
    // if (!this.data.storeId) {
    // 	wx.showToast({
    // 		icon: 'none',
    // 		title: '请添加门店',
    // 		duration: 1500
    // 	})
    // 	return
    // }
    if (!this.data.checked) {
      wx.showToast({
        icon: 'none',
        title: '请勾选用户协议',
        duration: 1500
      });
      return;
    }
    let dataJson = {};
    let urlStr = app.getNetAddresss("plugin.micro-communities.api.trick.publish");
    dataJson.cat_id = this.data.catid;
    dataJson.contents = this.data.releasecontents;
    dataJson.address = this.data.releaseaddress;
    dataJson.images = this.data.imgData;
    dataJson.title = this.data.releasetitle;
    dataJson.goods_id = this.data.goodsId;
    dataJson.store_id = this.data.storeId;
    dataJson.city = this.data.releasecity;
    dataJson.lat = this.data.releaselat;
    dataJson.lng = this.data.releaselnt;
    dataJson.ylat = this.data.releaselat;
    dataJson.ylng = this.data.releaselnt;
    dataJson.tid = this.data.stickid;
    dataJson.audio = this.data.audioPath;
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: dataJson,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          wx.reLaunch({
            url: '/packageC/micro_communities/microIndex/microIndex'
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {}
    });
  },
  protocolBtn(e) {
    let bol = e.detail;
    this.setData({
      checked: bol
    });
  },
  onClickLeft() {
    this.setData({
      classificationshow: false
    });
  },
  onClickRight() {
    this.setData({
      classificationshow: false
    });
  },
  commodityTitleClear() {
    this.setData({
      commodityTitle: ''
    });
  },
  commodityTitleInp(e) {
    let val = e.detail.value;
    this.setData({
      commodityTitle: val
    });
  },
  searchBtn() {
    this.getClassificationData();
  },
  selectCateId(e) {
    let id = e.currentTarget.dataset.id;
    let name = e.currentTarget.dataset.name;
    this.setData({
      catid: id,
      catname: name,
      classificationshow: false
    });
  },
  selectCateTwoId(e) {
    let id = e.currentTarget.dataset.id;
    let name = e.currentTarget.dataset.name;
    this.setData({
      catid: id,
      catname: name + '/' + e.currentTarget.dataset.cname,
      classificationshow: false
    });
  },
  onAddressLeft() {
    this.setData({
      Locationshow: false,
      suggestionshow: false,
      address_detail: ''
    });
  },
  onAddressRight() {
    this.setData({
      Locationshow: false,
      suggestionshow: false,
      address_detail: ''
    });
  },
  addressinpbtn(e) {
    var val = e.detail.value;
    this.addressinp(val);
  },
  addressinp(val) {
    var _this = this;
    if (!val) {
      this.setData({
        suggestionshow: false
      });
      return;
    }
    //调用关键词提示接口
    qqmapsdk.getSuggestion({
      //获取输入框值并设置keyword参数
      keyword: val, //用户输入的关键词，可设置固定值,如keyword:'KFC'
      //region:'北京', //设置城市名，限制关键词所示的地域范围，非必填参数
      sig: app.globalData.qqmapsig,
      success: function (res) { //搜索成功后的回调
        var sug = [];
        for (var i = 0; i < res.data.length; i++) {
          sug.push({ // 获取返回结果，放到sug数组中
            title: res.data[i].title,
            id: res.data[i].id,
            addr: res.data[i].address,
            city: res.data[i].city,
            district: res.data[i].district,
            latitude: res.data[i].location.lat,
            longitude: res.data[i].location.lng
          });
        }
        _this.setData({ //设置suggestion属性，将关键词搜索结果以列表形式展示
          suggestion: sug,
          suggestionshow: true
        });
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {

      }
    });
  },
  //数据回填方法
  backfill: function (e) {
    var id = e.currentTarget.id;
    for (var i = 0; i < this.data.suggestion.length; i++) {
      if (i == id) {
        this.setData({
          releaseaddress: this.data.suggestion[i].addr,
          releasecity: this.data.suggestion[i].city,
          releaselat: this.data.suggestion[i].latitude,
          releaselnt: this.data.suggestion[i].longitude,
          address_detail: '',
          suggestionshow: false,
          Locationshow: false
        });
      }
    }
  },
  onAddGoodsLeft() {
    this.setData({
      addgoodslistshow: false
    });
  },
  onAddGoodsRight() {
    this.setData({
      addgoodslistshow: false
    });
  },
  goodsdataClear() {
    this.setData({
      goodsdata: ''
    });
  },
  goodsdataInp(e) {
    let val = e.detail.value;
    this.setData({
      goodsdata: val
    });
  },
  searchGoodBtn() {
    this.getGoodsMessageData();
  },
  getGoodsMessageData() {
    let that = this;
    let json = {};
    json.goods_name = this.data.goodsdata;
    let urlStr = app.getNetAddresss("plugin.micro-communities.api.trick.getGoods");
    that.setData({
      goodsPage: 1 //数组拼接
    });
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            goodslistData: res.data.data,
            goodsTotal: res.data.last_page
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getGoodMoreData() {
    const that = this;
    that.data.goodsisLoadMore = false; // 防止多次请求分页数据
    if (this.data.goodsPage >= this.data.goodsTotal) {
      return;
    } else {
      this.data.goodsPage = this.data.goodsPage + 1;
      let urlStr = app.getNetAddresss("plugin.micro-communities.api.trick.getGoods");
      app._getNetWork({
        url: urlStr,
        data: {
          page: that.data.goodsPage,
          goods_name: that.data.goodsdata
        },
        success: function (resdata) {
          var res = resdata.data;
          that.data.goodsisLoadMore = true;
          if (res.result == 1) {
            let myData = res.data.data;
            that.setData({
              goodslistData: that.data.goodslistData.concat(myData) //数组拼接
            });
          } else {
            that.data.goodsPage = that.data.goodsPage - 1;
            that.data.goodsisLoadMore = false;
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  setGoodsId(e) {
    let id = e.currentTarget.dataset.id;
    this.setData({
      goodsId: id
    });
    let selectgoodsData = {};
    for (let i = 0; i < this.data.goodslistData.length; i++) {
      if (this.data.goodsId == this.data.goodslistData[i].id) {
        selectgoodsData.id = this.data.goodslistData[i].id;
        selectgoodsData.title = this.data.goodslistData[i].title;
        selectgoodsData.thumb = this.data.goodslistData[i].thumb;
        selectgoodsData.price = this.data.goodslistData[i].price;
        selectgoodsData.market_price = this.data.goodslistData[i].market_price;
        selectgoodsData.show_sales = this.data.goodslistData[i].show_sales;
        break;
      }
    }
    this.setData({
      selectgoodsData: selectgoodsData,
      addgoodslistshow: false
    });
  },
  storedataClear() {
    this.setData({
      storedata: ''
    });
  },
  storedataInp(e) {
    let val = e.detail.value;
    this.setData({
      storedata: val
    });
  },
  searchStoreBtn() {
    this.getStoreMessageData();
  },
  setStoreId(e) {
    let id = e.currentTarget.dataset.id;
    this.setData({
      storeId: id
    });
    let selectstoreData = {};
    for (let i = 0; i < this.data.storelistData.length; i++) {
      if (this.data.storeId == this.data.storelistData[i].id) {
        selectstoreData.id = this.data.storelistData[i].id;
        selectstoreData.thumb = this.data.storelistData[i].thumb;
        selectstoreData.store_name = this.data.storelistData[i].store_name;
        selectstoreData.address = this.data.storelistData[i].address;
        break;
      }
    }
    this.setData({
      selectstoreData: selectstoreData,
      storeshow: false
    });
  },
  protocolLeft() {
    this.setData({
      protocolshow: false
    });
  },
  onStoreLeft() {
    this.setData({
      storeshow: false
    });
  },
  onStoreRight() {
    this.setData({
      storeshow: false
    });
  },
  getMicroCommentDetails() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.micro-communities.api.trick.getStrickDetail");
    let dataJson = {
      tid: this.data.stickid
    };
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: dataJson,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            catid: res.data.cat_id,
            catname: res.data.cat_name,
            releasecontents: res.data.contents,
            releaseaddress: res.data.address
          });
          let has_many_image = res.data.has_many_image;
          let imgData = that.data.imgData;
          for (let i = 0; i < has_many_image.length; i++) {
            imgData.push(has_many_image[i].url);
          }
          that.setData({
            imgData: imgData,
            releasetitle: res.data.title,
            goodsId: res.data.goods_id,
            storeId: res.data.store_id,
            releasecity: res.data.city,
            releaselat: res.data.ylat,
            releaselnt: res.data.ylng,
            audioList: res.data.audio_src,
            audioPath: res.data.audio
          });
          let has_one_goods = res.data.has_one_goods;
          if(has_one_goods){
            that.setData({
              'selectgoodsData.id': has_one_goods.id,
              'selectgoodsData.title': has_one_goods.title,
              'selectgoodsData.thumb': has_one_goods.thumb,
              'selectgoodsData.price': has_one_goods.price,
              'selectgoodsData.market_price': has_one_goods.market_price,
              'selectgoodsData.show_sales': has_one_goods.show_sales
            });
          }
          
          let has_one_store = res.data.has_one_store;
          if(has_one_store){
            that.setData({
              'selectstoreData.id': has_one_store.id,
              'selectstoreData.thumb': has_one_store.thumb,
              'selectstoreData.store_name': has_one_store.store_name,
              'selectstoreData.address': has_one_store.address
            });
          }
          
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {}
    });
  },
  updataAudio(e){
    console.log(e.detail);
    this.data.audioPath.push({
      file: e.detail.img,
      duration: e.detail.duration||0
    });
    this.data.audioList.push({file:e.detail.img_url,duration: e.detail.duration||0});
    this.setData({audioList:this.data.audioList});
  },
  delAudio(e) {
    let index = e.currentTarget.dataset.index;
    let _this = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除该音频?',
      success (res) {
        if (res.confirm) {
          _this.data.audioPath.splice(index, 1);
          _this.data.audioList.splice(index, 1);
          _this.setData({audioList:_this.data.audioList});
        }
      }
    })
  }
});